/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Reflection;
using System.Windows.Media.Effects;
using ShaderEffects;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace myBoard.Framework
{
    public class MagnetEx : IMagnet
    {
        #region Properties and fields

        private IMagnet _magnet;
        private string _magnetID;
        private string _fullyQualifiedName;
        private bool _isFlipping;
        private MagnetSides _activeSide;
        private Point _lastClickedPoint;
        private Point _startPosition;
        private Grid _frozenContainer = new Grid();
        public event OnFlipRequested FlipRequested;
        public event EventHandler CloseMyBoardRequested;
        public Version Version { get; set; }


        public IMagnet Magnet
        {
            get { return _magnet; }
        }

        public string MagnetID
        {
            get
            {
                return _magnetID;
            }            
            set
            {
                _magnetID = value;
            }
        }

        /// <summary>
        /// This is your magnet ID in the Magnets Store. Each magnet must have a unique StoreID.
        /// </summary>
        public string StoreID 
        {
            get 
            {
                if (_magnet != null)
                    return _magnet.StoreID;
                else
                    return "NOT_DEFINED";
            }
        }

        public string FullyQualifiedName
        {
            get
            {
                return _fullyQualifiedName;                
            }
            set
            {
                _fullyQualifiedName = value;
            }
        }

        public string MagnetName
        {
            get
            {
                return _magnet.MagnetName;
            }
        }

        public System.Windows.Point StartPosition
        {
            get
            {
                return _startPosition;
            }
            set
            {
                _startPosition = value;
            }
        }

        public System.Windows.Point LastClickedPoint
        {
            get
            {
                return _lastClickedPoint;
            }            
        }


        public MagnetSides ActiveSide
        {
            get { return _activeSide; }
        }

        #endregion

        #region Constructors

        public MagnetEx()
        {}

        public MagnetEx(IMagnet magnet)
        {
            _magnet = magnet;
            _magnetID = Guid.NewGuid().ToString();
            if(magnet is IFlip)
                ((IFlip)_magnet).FlipRequested += new OnFlipRequested(Magnet_FlipRequested);

            ((UIElement)_magnet).MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(MagnetEx_MouseLeftButtonDown);
        }

        public MagnetEx(IMagnet magnet,MagnetEx deserializedMagnet)
        {
            _magnet = magnet;
            _magnetID = deserializedMagnet._magnetID;
            _startPosition = deserializedMagnet.StartPosition;
            if (magnet is IFlip)
                ((IFlip)_magnet).FlipRequested += new OnFlipRequested(Magnet_FlipRequested);

            ((UIElement)_magnet).MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(MagnetEx_MouseLeftButtonDown);
        }

        #endregion

        #region Events

        void Magnet_CloseMyBoardRequested(object sender, EventArgs e)
        {
            if (CloseMyBoardRequested != null)
                CloseMyBoardRequested(sender, e);
        }

        void Magnet_FlipRequested(MagnetSides targetSide)
        {
            try
            {
                if (FlipRequested != null)
                    FlipRequested(targetSide);

                Flip(targetSide);
            }
            catch (Exception ex)
            {
                ExceptionsManager.LogException("myBoard Framework", ex, true);
            }
        }

        void MagnetEx_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _lastClickedPoint = Mouse.GetPosition((UIElement)_magnet);
        }

        #endregion

        #region Methods

        #region 3D Flip method

        /// <summary>
        /// Flip the magnet to the specified side
        /// </summary>
        /// <param name="side">Side you want the magnet to rotate to.</param>

        public void Flip(MagnetSides side)
        {
            if (!_isFlipping)
            {
                _isFlipping = true;
                IFlip magnet = _magnet as IFlip;
                FrameworkElement backside = magnet.GetBackSide();
                FrameworkElement frontside = magnet.GetFrontSide();

                if (backside == null || frontside == null)
                {
                    _isFlipping = false;
                    return;
                }

                Flipper flipper = new Flipper();
                Grid flipZone = new Grid();
                flipZone.Width = frontside.ActualWidth;
                flipZone.Height = frontside.ActualHeight;
                Panel parent = frontside.Parent as Panel;
                parent.Children.Add(flipZone);
                backside.Visibility = Visibility.Visible;
                frontside.Visibility = Visibility.Visible;
                flipper.SetBackSideContent(backside);
                flipper.SetFrontSideContent(frontside);
                backside.Visibility = Visibility.Hidden;
                frontside.Visibility = Visibility.Hidden;
                flipper.Loaded += new RoutedEventHandler(delegate
                {
                    if (side == MagnetSides.Front)
                    {
                        if (_activeSide != MagnetSides.Front)
                            flipper.FlipToFrontSide();
                    }

                    else if (side == MagnetSides.Back)
                    {
                        if (_activeSide != MagnetSides.Back)
                            flipper.FlipToBackSide();
                    }

                    else
                        return;

                    flipper.FlipToBackSideCompleted += new EventHandler(delegate
                    {
                        frontside.Visibility = Visibility.Hidden;
                        backside.Visibility = Visibility.Visible;
                        flipZone.Children.Clear();
                        flipper = null;
                        _isFlipping = false;
                        _activeSide = MagnetSides.Back;
                    });

                    flipper.FlipToFrontSideCompleted += new EventHandler(delegate
                    {
                        frontside.Visibility = Visibility.Visible;
                        backside.Visibility = Visibility.Hidden;
                        flipZone.Children.Clear();
                        flipper = null;
                        _isFlipping = false;
                        _activeSide = MagnetSides.Front;
                    });
                });
                flipZone.Children.Add(flipper);
            }
        }

        public void Freeze()
        {
            return;
            if (Magnet is IFlip)
            {
                try
                {
                    var magnet = Magnet as IFlip;
                    Panel content = null;
                    
                    if (_activeSide == MagnetSides.Front)
                        content = magnet.GetFrontSide();
                    else
                        content = magnet.GetBackSide();

                    var parent = content.Parent as Panel;
                    var ib = new ImageBrush(Tools.GetBitmapSourceFromFrameworkElement(content));
                    content.Visibility = Visibility.Collapsed;
                    var size = GetSize(content);
                    _frozenContainer.Width = size.Width;
                    _frozenContainer.Height = size.Height;
                    _frozenContainer.Margin = content.Margin;
                    _frozenContainer.HorizontalAlignment = content.HorizontalAlignment;
                    _frozenContainer.VerticalAlignment = content.VerticalAlignment;
                    _frozenContainer.Background = ib;
                    if (!parent.Children.Contains(_frozenContainer))
                    {
                        parent.Children.Add(_frozenContainer);
                    }
                }
                catch
                { }
                //var panel = (IFlip)Magnet
            }
        }

        public void UnFreeze()
        {
            return;
            if (Magnet is IFlip)
            {
                var magnet = Magnet as IFlip;
                Panel content = null;

                if (_activeSide == MagnetSides.Front)
                    content = magnet.GetFrontSide();
                else
                    content = magnet.GetBackSide();

                content.Visibility = Visibility.Visible;
                var parent = content.Parent as Panel;
                if (parent.Children.Contains(_frozenContainer))
                {
                    parent.Children.Remove(_frozenContainer);
                }
            }
        }

        private Size GetSize(FrameworkElement element)
        {
            double elementWidth = 0;
            double elementHeight = 0;

            if (double.IsNaN(element.ActualWidth) || element.ActualWidth == 0)
                elementWidth = element.Width;
            else
                elementWidth = element.ActualWidth;

            if (double.IsNaN(element.ActualHeight) || element.ActualHeight == 0)
                elementHeight = element.Height;
            else
                elementHeight = element.ActualHeight;

            return new Size(elementWidth, elementHeight);
        }

        #endregion

        #endregion

        #region IMagnet Members

        public void SaveState()
        {
            if (_magnet is IRequiresStorage)
            {
                ((IRequiresStorage)_magnet).SaveState();
            }
        }

        public void Terminate()
        {
            _magnet.Terminate();
        }

        #endregion

        #region IMagnet Members


        public BitmapImage Icon
        {
            get
            {
                return _magnet.Icon;
            }
        }

        public BitmapImage Thumbnail
        {
            get
            {
                return _magnet.Thumbnail;
            }
        }

        #endregion
    }
}